package com.itheima.night;

import com.itheima.afternoon.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Demo02 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazz = Class.forName("com.itheima.afternoon.Student");
        //method1(clazz);
        //method2(clazz);
        Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class,int.class);
        declaredConstructor.setAccessible(true);
        //带参构造需要直接赋值，不能用get，set方法
        Student student = (Student) declaredConstructor.newInstance("张三",23);
        System.out.println(student);
    }

    private static void method2(Class clazz) throws InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException {
//        Student student = (Student) clazz.newInstance();
        Constructor declaredConstructor = clazz.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Student student = (Student) declaredConstructor.newInstance();
        System.out.println(student);
        Field name = clazz.getField("name");
        Field stuId = clazz.getField("stuId");
        name.set(student,"张三");
        stuId.set(student,"1001");
        System.out.println(student);
    }

    private static void method1(Class clazz) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Constructor constructor = clazz.getConstructor(String.class,String.class,int.class);
        constructor.setAccessible(true);
        Student student = (Student) constructor.newInstance("10001","zhangsan",23);
        System.out.println(student);
    }
}
